<template>
  <div class="share-document-container">
    <div class="header">
      <h1>{{ document.title }}</h1>
      <div class="status">
        <span>在线用户: {{ onlineUsers.length }}</span>
        <span v-if="isSaving">正在自动保存...</span>
      </div>
    </div>

    <!-- 文档类型切换 -->
    <div class="document-type-switcher">
      <button :class="{ active: currentType === 'word' }" @click="switchType('word')">
        富文本文档 (Word)
      </button>
      <button :class="{ active: currentType === 'excel' }" @click="switchType('excel')">
        电子表格 (Excel)
      </button>
    </div>

    <!-- 嵌套子组件 -->
    <div class="editor-container">
      <WordComponent
        v-if="currentType === 'word'"
        :content="wordContent"
        @content-change="handleWordContentChange"
      />
      <ExcelComponent
        v-else-if="currentType === 'excel'"
        :content="luckysheetContent"
        @change="handleExcelChange"
        @destroy="destroyLuckysheet"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { io } from 'socket.io-client';
import WordComponent from '@/components/WordComponent.vue'; // 引入Word子组件
import ExcelComponent from '@/components/ExcelComponent.vue'; // 引入Excel子组件

// 1. 响应式数据
const props = defineProps({
  documentId: {
    type: String,
    required: true
  }
});

const currentType = ref('word');
const wordContent = ref('');
const luckysheetContent = ref(null);
const document = ref({ title: '加载中...' });
const onlineUsers = ref([]);
const isSaving = ref(false);
const socket = ref(null);

// 2. 初始化函数
const init = async () => {
  await loadDocumentData();
  initSocketConnection();
};

// 3. 加载文档数据
const loadDocumentData = async () => {
  // 模拟接口数据，实际替换为真实API请求
  document.value = { id: props.documentId, title: '项目计划书' };
  wordContent.value = '<p>这是一个共享的富文本文档。</p><p>请在此处输入内容...</p>';
  luckysheetContent.value = {
    "name": "表格1",
    "status": "1",
    "data": [["A1", "B1"], ["A2", "B2"]],
    "config": { "row": { "len": 100 }, "column": { "len": 26 } }
  };
  document.title = document.value.title;
};

// 4. Socket连接与实时同步
const initSocketConnection = () => {
  socket.value = io('http://localhost:3000');

  socket.value.on('connect', () => {
    console.log('Socket connected');
    socket.value.emit('join-document', { documentId: props.documentId });
  });

  // 接收完整文档数据
  socket.value.on('document-data', (data) => {
    if (data.type === 'word' && currentType.value === 'word') {
      wordContent.value = data.content;
    } else if (data.type === 'excel' && currentType.value === 'excel') {
      luckysheetContent.value = data.content;
    }
  });

  // 接收实时更新
  socket.value.on('update', (update) => {
    isSaving.value = true;
    if (update.type === 'word' && currentType.value === 'word') {
      wordContent.value = update.content;
    } else if (update.type === 'excel' && currentType.value === 'excel') {
      window.luckysheet?.applyChanges(update.changes);
    }
    setTimeout(() => { isSaving.value = false; }, 1000);
  });

  socket.value.on('online-users', (users) => {
    onlineUsers.value = users;
  });

  socket.value.on('disconnect', () => {
    console.log('Socket disconnected');
  });
};

// 5. 切换文档类型
const switchType = (type) => {
  if (currentType.value === type) return;

  // 切换前保存当前内容
  if (currentType.value === 'word') {
    socket.value.emit('push-full-data', {
      documentId: props.documentId,
      type: 'word',
      content: wordContent.value
    });
  } else if (currentType.value === 'excel') {
    destroyLuckysheet(); // 触发Excel组件销毁
  }

  currentType.value = type;
  socket.value.emit('request-full-data', { documentId: props.documentId, type: type });
};

// 6. 接收Word组件内容变化
const handleWordContentChange = (content) => {
  socket.value.emit('update', {
    documentId: props.documentId,
    type: 'word',
    content: content
  });
};

// 7. 接收Excel组件变化
const handleExcelChange = (changes) => {
  isSaving.value = true;
  socket.value.emit('update', {
    documentId: props.documentId,
    type: 'excel',
    changes: changes
  });
  setTimeout(() => { isSaving.value = false; }, 500);
};

// 8. 销毁Excel实例
const destroyLuckysheet = () => {
  if (window.luckysheet) {
    window.luckysheet.destroy();
    window.luckysheet = null;
  }
};

// 9. 生命周期
onMounted(() => init());
onUnmounted(() => {
  socket.value?.disconnect();
  destroyLuckysheet();
});

// 监听Excel类型切换，触发组件重新渲染
watch(currentType, (newVal) => {
  if (newVal === 'excel' && luckysheetContent.value) {
    setTimeout(() => {
      window.luckysheet?.create({
        container: 'luckysheet-container',
        data: luckysheetContent.value.data,
        config: luckysheetContent.value.config
      });
    }, 0);
  }
});
</script>

<style scoped>
.share-document-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
}
.document-type-switcher {
  display: flex;
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
  gap: 10px;
}
.document-type-switcher button {
  padding: 8px 16px;
  border: 1px solid #ccc;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
}
.document-type-switcher button.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}
.editor-container {
  flex: 1;
  overflow: auto;
  padding: 20px;
}
.status {
  color: #666;
  font-size: 0.9em;
}
</style>